package com.xiaolv.web.controller;

import com.xiaolv.web.model.SysLog;
import com.xiaolv.web.service.LogService;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

/**
 * 日志数据表测试
 */
@Controller
@RequestMapping(value = "/log")
public class LogController {

    @Autowired
    private LogService logService;

    /**
     * mybatis plus添加
     *
     * @return
     * @throws Exception
     */
    @ResponseBody
    @GetMapping(value = "add")
    public Boolean add() {
        SysLog o = new SysLog();
        o.setTitle("测试");
        o.setCreateTime(LocalDateTime.now());
        logService.save(o);

        o.setTitle("测试2");
        Calendar cal = Calendar.getInstance();
        cal.add(Calendar.DAY_OF_YEAR, -1);
        o.setCreateTime(DateToLocaleDate(cal.getTime()));
        logService.save(o);
        return true;
    }

    @ResponseBody
    @GetMapping(value = "list")
    public List<SysLog> list() {

        //查询所有表
        List<SysLog> list = logService.list();

        //查询两张表的数据，2天
        List<SysLog> list2 = logService.list(Wrappers.<SysLog>lambdaQuery()
                .between(SysLog::getCreateTime, "2020-10-08", "2020-10-09"));

        return list;
    }

    /**
     * date转localDate
     *
     * @param date
     * @return
     */
    public static LocalDateTime DateToLocaleDate(Date date) {
        Instant instant = date.toInstant();
        ZoneId zoneId = ZoneId.systemDefault();
        return instant.atZone(zoneId).toLocalDateTime();
    }
}
